/**
 * 
 */
package com.jd.event;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;

/**
 * @author luolishu
 * 
 */
public class EventContainer {
	 
	public static final String THREAD_POOL_SIZE="threadpool.size";
	ScheduedEventReposity reposity = new ScheduedEventReposity();
	EventTrigger trigger = new EventTrigger();
	Set<String> groups=new HashSet<String>();

	public void createGroup(String group) {
		if(groups.contains(group)){
			throw new EventException("duplicated group!group=["+group+"] is exist!");
		}
		
		reposity.addQueue(group, new DelayQueue<EventTarget>());
		EventTrigger.addListeners(group, new ArrayList<EventListener>());
		ExecutorService threadPool = Executors.newFixedThreadPool(1);
		EventTrigger.addGroup(group, threadPool);
		groups.add(group);
	}
	public void createGroup(String group,Properties properties) {
		if(groups.contains(group)){
			throw new EventException("duplicated group!group=["+group+"] is exist!");
		}
		 
		reposity.addQueue(group, new DelayQueue<EventTarget>()); 
		String threadPoolSize=properties.getProperty(THREAD_POOL_SIZE);
		
		EventTrigger.addListeners(group, new ArrayList<EventListener>());
		ExecutorService threadPool = null;
		if(StringUtils.isNotBlank(threadPoolSize)){
			threadPool = Executors.newFixedThreadPool(Integer.valueOf(threadPoolSize));
		}else{
			threadPool = Executors.newFixedThreadPool(1);
		}
		EventTrigger.addGroup(group, threadPool);
		groups.add(group);
	}
	public void addListeners(String group, List<EventListener> listeners) {
		EventTrigger.addListeners(group, listeners);
	}

	public void addListener(String group, EventListener listener) {
		EventTrigger.addListener(group, listener);
	}

	public ScheduedEventReposity getReposity() {
		return reposity;
	}

	public EventTrigger getTrigger() {
		return trigger;
	}

}
